@extends('layouts.app')

@section('content')
<div class="content-header">
    <h1>批量部署</h1>
    <ol class="breadcrumb">
      <li><a href="{{ url('/') }}"><i class="fa fa-dashboard"></i> 首页</a></li>
      <li class="active">批量部署</li>
    </ol>
  </div>
<div class="content">
    <div class="danger-box">
        <div class="alert alert-danger hidden" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <span class="msg">
                    
            </span>
        </div>
    </div>
    <div class="success-box">
        <div class="alert alert-success hidden" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <span class="msg">
                    
            </span>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    部署列表
                </div>
                <div class="panel-body">
                    <p style="text-align: right">
                        <button id="deploy" class="btn btn-warning">执行批量部署</button>
                    </p>
                    
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <table class="table table-bordered table-responsive table-striped">
                              <caption class="form-inline">
                                <div class="form-group">
                                  <label>选择要部署的分支：</label>
                                  <select name="branch-select" class="form-control form-group-sm" data-project-id="{{\request()->route('project_id')}}">
                                  </select>
                                </div>
                                
                              </caption>
                                <tr>
                                    <th>要部署的服务器</th>
                                    <th>namespace</th>
                                    <th>name</th>
                                </tr>
                                @foreach ($list as $setting)
                                <tr>
                                    <td>
                                        <label><input type="checkbox" name="setting[]" data-project-id="{{ $setting['repo_id'] }}" value="{{ $setting['id'] }}"> 选我</label>
                                    </td>
                                    <td>
                                        {{ substr(substr(parse_url($setting['repo_url'])['path'],0,-4),1) }}
                                    </td>
                                    <td>
                                        {{ $setting['name'] }}
                                    </td>
                                </tr>
                                @endforeach
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div id="option_tpl">
    <option value=""></option>
</div>

@endsection

@section('script')
<script>
  $(function () {

    $('#deploy').click(function () {
      var self = $(this);
      self.attr('disabled', 'disabled');
      $('.alert:visible').remove();
      var checked = [];
      var select = $('select[name="branch-select"]').find('option:selected');
      $('input[type="checkbox"]:checked').each(function () {
        checked.push({
          project_id: $(this).data('project-id'),
          setting_id: $(this).val().trim(),
          branch: select.val().trim(),
          checkout_sha: select.data('checkout-sha'),
        });
      });

      if (checked.length == 0) {
        self.removeAttr('disabled');
        var msg_box = $('.danger-box').clone();
        msg_box.find('.alert-danger').removeClass('hidden').find('span.msg').html('请选择要部署的项目');

        $('#deploy').parent().after(msg_box.html());
        return false;
      }

      $.post('/batch_deploy', {data: checked}, function (e) {
        if (e.success_msg !== undefined) {
          var msg_box = $('.success-box').clone();
          msg_box.find('.alert-success').removeClass('hidden').find('span.msg').html(e.success_msg);
          $('input[type="checkbox"]:checked').trigger('click');
        } else {
          var msg_box = $('.danger-box').clone();
          msg_box.find('.alert-danger').removeClass('hidden').find('span.msg').html(e.error_msg);
        }

        $('#deploy').parent().after(msg_box.html());
        self.removeAttr('disabled');

      }, 'json');
    });

    var details = {};
    var ajax_arr = [];
    $('select').each(function () {
      var project_id = $(this).data('project-id');
      var self = $(this);
      if (details['setting_' + project_id] === undefined || details['setting_' + project_id] === '') {
        $(this).find('option:first').text('获取分支中，稍等。。');
        var option_tpl = $('#option_tpl').clone();
        var _this_ajax = $.get("/project/branches/" + project_id, {}, function (e) {
          var option_html = '';
          $.each(e, function (m, n) {
            var tag = m == 'tags' ? '【Tag】' : '【分支】';
            $.each(n, function (key, value) {
              var message = m == 'tags' ? '（' + value.message + '）' : '';
              option_tpl.find('option').text(tag + value.name + message);
              option_tpl.find('option').val(value.name);
              option_tpl.find('option').attr('data-checkout-sha', value.commit.id)
              option_html += option_tpl.html();
            });
          });

          self.html(option_html);
          details['setting_' + project_id] = option_html;
        }, 'json');

        ajax_arr.push(_this_ajax);
      }
    });

    $('.nav-tabs').click(function () {
      for (var i = 0; i < ajax_arr.length; i++) {
        ajax_arr[i].abort();
      }
    });
  });

</script>
@endsection